package com.action.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.action.childbase.ChildBaseActivity;
import com.action.service.pressenter.IndexPressenter;
import com.base.app_core.base.ActionPacketView;
import com.base.app_core.model.Config;
import com.base.app_core.model.Paginated;
import com.base.app_core.model.dto.Advertiser;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.Preferences;
import com.base.app_core.util.XYBAUtils;
import com.base.app_core.util.log.F;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.Glide;
import com.tencent.map.lib.util.StringUtil;
import com.xinglai.yun.Application;
import com.xinglai.yun.R;
import com.xinglai.yun.wxapi.WXEntryActivity;

import java.util.Collection;
import java.util.List;
import java.util.Random;

import butterknife.BindView;

public class XYBSpreahActivity extends ChildBaseActivity<IndexPressenter> implements ActionPacketView.IndexAction {


    private static final String SKIP_TEXT = "跳过%d";
    private FrameLayout frameLayout;

    @BindView(R.id.default_container)
    ImageView defaultContainer;

    @BindView(R.id.skip_view)
    TextView skipView;

    private boolean canJump;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_spreah_actvity;
    }

    @Override
    protected String[] getPermissions() {
        return AppConstants.appPermission;
    }

    @Override
    protected void initView() {
        super.initView();
        mPresenter.getSystemConfig();
        frameLayout = (FrameLayout) findViewById(R.id.container);
    }


    Handler handler = new Handler(Looper.getMainLooper());
    int count = 1;
    Runnable r = new Runnable() {
        @Override
        public void run() {
            if (count == 0) {
                skipView.setVisibility(View.VISIBLE);
                skipView.setText(getResources().getString(R.string.click_to_skip));
                skipView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        jump();
                    }
                });

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        jump();
                    }
                }, 500);
            } else {
                handler.postDelayed(this, 1000);
                skipView.setVisibility(View.VISIBLE);
                skipView.setText(String.format(SKIP_TEXT, count));
                count = count - 1;
            }
        }
    };

    private void setDefautContainerVisible(int visible) {
        if (visible == View.GONE) {
            handler.removeCallbacks(r);
        }
        defaultContainer.setVisibility(visible);
    }

    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(this);
    }

    @Override
    protected void initData() {
        super.initData();
    }

    private void jump() {
        if (canJump) {
            String jwToken = Preferences.getDefault().getString(AppConstants.SP.JWTOKEN, null);
            if (StringUtil.isEmpty(jwToken)) {
                startActivity(new Intent(this, WXEntryActivity.class)
                        .putExtra(AppConstants.EXTRA.IS_FROM_LOGIN, true));
            }  else {
                Intent intent = new Intent();
                intent.setClass(this, XYBMainActiviy.class);
                startActivity(intent);
            }
            this.finish();
        } else {
            canJump = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        canJump = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        canJump = true;
        if (canJump) {
            jump();
        }

    }


    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        super.notifyData(object, tClass, paginated);
        if (object instanceof Collection) {
            if (tClass == Advertiser.class) {
                dismissProgress();
                List<Advertiser> advertiserList = (List<Advertiser>) object;
                if (XYBAUtils.isEmpty(advertiserList)) {
                    return;
                }

                Random random = new Random();
                Advertiser advertiser = advertiserList.get(random.nextInt(advertiserList.size()));
                final String url = advertiser.getUrl();
                String img = advertiser.getImg();
                Preferences.putString(AppConstants.SP.ADVERTISE_URL, url);
                Preferences.putString(AppConstants.SP.ADVERTISE_IMG, img);
                setDefautContainerVisible(View.VISIBLE);
                Glide.with(this).load(img).asBitmap().centerCrop().into(defaultContainer);
                if (!StringUtils.isEmpty(url)) {
                    frameLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (XYBAUtils.checkAliApkExist(XYBSpreahActivity.this)) {
                                try {
                                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                                    startActivity(intent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                showToast("请安装支付宝");
                            }
                        }
                    });
                }
            } else if (tClass == Config.class) {
                List<Config> configs = (List<Config>) object;
                for (Config c : configs) {
                    //支付方式
                    if ("payTypeLimit".equals(c.getCkey()) && !StringUtils.isEmpty(c.getCvalue())) {
                        Preferences.putString(AppConstants.SP.PAY_TYPE, c.getCvalue());
                    }

                    if ("withDrawTypeLimit".equals(c.getCkey()) && !StringUtils.isEmpty(c.getCvalue())) {
                        Preferences.putString(AppConstants.SP.WITH_DRAW_TYPE_LIMIT, c.getCvalue());
                    }

                    if ("isDebug".equals(c.getCkey()) && !StringUtils.isEmpty(c.getCvalue())) {
                        F.w("cvalue===========>" + c.getCvalue());
                        if ("false".equals(c.getCvalue())) {
                            Preferences.putBoolean(AppConstants.SP.IS_DEBUG, false);
                        } else {
                            Preferences.putBoolean(AppConstants.SP.IS_DEBUG, true);
                        }
                    }
                    if ("appName".equals(c.getCkey()) && !StringUtils.isEmpty(c.getCvalue())) {
                        AppConstants.APPNAME = c.getCvalue();
                    }

                    if ("appIcon".equals(c.getCkey()) && !StringUtils.isEmpty(c.getCvalue())) {
                        AppConstants.APPICON = c.getCvalue();
                    }

                    if ("isSimCardNeed".equals(c.getCkey()) && !StringUtils.isEmpty(c.getCvalue())) {
                        if ("1".equals(c.getCvalue())) {
                            Preferences.putBoolean(AppConstants.SP.IS_NEED_SIM, true);
                        } else {
                            Preferences.putBoolean(AppConstants.SP.IS_NEED_SIM, false);
                        }
                    }

                    if ("shareScalePercent".equals(c.getCkey()) && !StringUtils.isEmpty(c.getCvalue())) {
                        Preferences.putString(AppConstants.SP.SHARE_SCALE_PERCENT, c.getCvalue());
                    }
                }
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Application application = (Application) getApplication();
        application.adViewSpreadManager.viewGroup = null;
        application.adViewSpreadManager.destroy();
    }

    @Override
    public void onTimeCount(int tick) {

    }
}
